<script setup>
/*----------------------* 用户管理页面 *----------------------*/

import {onMounted, ref, watch} from 'vue';
import {ElMessage} from 'element-plus';
import http from "@/request/http.js";
import {useRoute} from "vue-router";

const route = useRoute();

// 用户列表数据（数组类型，匹配API返回的records）
const userList = ref([]);

// 选中的用户ID数组
const selectedUserIds = ref([]);

// 搜索表单数据
const searchForm = ref({
  username: '',  // 账号
  email: ''      // 邮箱
});

// 分页参数
const pagination = ref({
  currentPage: 1,  // 当前页
  pageSize: 10,    // 每页条数（与后端默认保持一致）
  total: 0,        // 总条数
  pages: 0         // 总页数
});

// 封禁相关变量
const banDialog = ref(false);  // 封禁模态框显示状态
const banForm = ref({
  userIds: [],       // 选中的用户ID
  userReason: '',    // 封禁原因
  userBanType: '',   // 封禁类型
});

// 处理多选框选择事件
const handleSelectionChange = (selection) => {
  selectedUserIds.value = selection.map(item => item.userId);
};

// 搜索方法：加载用户列表
const handleSearch = async () => {
  try {
    const params = {
      currentPage: pagination.value.currentPage,
      pageSize: pagination.value.pageSize,
      username: searchForm.value.username,
      email: searchForm.value.email
    };
    const response = await http.get("/system/getList", {params});
    if (response.code === 200) {
      userList.value = response.data.records;
      pagination.value = {
        ...pagination.value,
        total: response.data.total,
        pages: response.data.pages
      };
    } else {
      ElMessage.error('获取数据失败：' + response.msg);
    }
  } catch (error) {
    ElMessage.error('网络错误，无法获取用户列表');
    console.error(error);
  }
};

// 处理账号状态变更
const handleStatusChange = async (row) => {
  try {
    const response = await http.put("/system/updateStatus", {
      userId: row.userId,
      userStatusId: row.userStatusId
    });

    if (response.code === 200) {
      ElMessage.success('状态更新成功');
    } else {
      row.userStatusId = row.userStatusId === 0 ? 1 : 0;
      ElMessage.error('状态更新失败：' + response.msg);
    }
  } catch (error) {
    row.userStatusId = row.userStatusId === 0 ? 1 : 0;
    ElMessage.error('网络错误，状态更新失败');
    console.error(error);
  }
};

// 重置搜索
const handleReset = () => {
  searchForm.value = {
    username: '',
    email: ''
  };
  pagination.value.currentPage = 1;
  handleSearch();
};

// 打开封禁模态框
const handleAdd = () => {
  if (selectedUserIds.value.length === 0) {
    ElMessage.warning('请先选择要封禁的用户');
    return;
  }
  banForm.value = {
    userIds: [...selectedUserIds.value],
    userReason: '',
    userBanType: ''
  };
  banDialog.value = true;
};

// 提交封禁操作
const confirmBan = async () => {
  if (!banForm.value.userReason) {
    ElMessage.warning('请输入封禁原因');
    return;
  }
  if (!banForm.value.userBanType) {
    ElMessage.warning('请选择封禁类型');
    return;
  }

  try {
    const response = await http.put("/system/banUsers", banForm.value);
    if (response.code === 200) {
      ElMessage.success('封禁成功');
      banDialog.value = false;
      handleSearch();
    } else {
      ElMessage.error('封禁失败：' + response.msg);
      banDialog.value = false;
    }
  } catch (error) {
    ElMessage.error('网络错误，封禁失败');
    console.error(error);
    banDialog.value = false;
  }
};

// 修改用户
const handleEdit = (row) => {
  ElMessage.info(`修改用户：${row.username}`);
};

// 删除用户
const handleDelete = (row) => {
  ElMessage.info(`删除用户：${row.username}`);
};

// 分页大小变更
const handleSizeChange = (val) => {
  pagination.value.pageSize = val;
  pagination.value.currentPage = 1;
  handleSearch();
};

// 当前页变更
const handleCurrentChange = (val) => {
  pagination.value.currentPage = val;
  handleSearch();
};

// 关闭模态框
const closeBanDialog = () => {
  banDialog.value = false;
};

// 监听路由变化，当路由参数或路径变化时刷新数据
watch(
    () => route.fullPath, // 监听完整路径变化
    () => {
      handleSearch(); // 调用数据刷新方法
    }
);

// 组件初始化时加载数据
onMounted(() => {
  handleSearch();
});
</script>

<template>
  <div class="user-container">
    <!-- 搜索区域 -->
    <div class="search-form">
      <el-form :model="searchForm" inline>
        <el-form-item label="账号">
          <el-input
              v-model="searchForm.username"
              clearable
              placeholder="请输入账号"
          />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input
              v-model="searchForm.email"
              clearable
              placeholder="请输入邮箱"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="operation-buttons">
      <el-button type="primary" @click="handleAdd">封禁选中的用户</el-button>
    </div>

    <!-- 用户列表表格：使用排序序号替代用户ID -->
    <el-table
        :data="userList"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"/>
      <!-- 排序序号列（替换原用户ID列） -->
      <el-table-column align="center" label="序号" width="70">
        <template #default="scope">
          {{ (pagination.currentPage - 1) * pagination.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="账号" prop="username" width="120"/>
      <el-table-column label="邮箱" prop="email" width="200"/>
      <el-table-column label="年龄" prop="age" width="60">
        <template #default="scope">
          {{ scope.row.age === '' ? '保密' : scope.row.age }}
        </template>
      </el-table-column>
      <el-table-column label="性别" prop="gender" width="60">
        <template #default="scope">
          {{ scope.row.gender === 1 ? '男' : scope.row.gender === 0 ? '女' : '保密' }}
        </template>
      </el-table-column>
      <el-table-column label="头像" prop="avatar" width="60">
        <template #default="scope">
          <el-avatar :src="scope.row.avatar" size="small"/>
        </template>
      </el-table-column>
      <el-table-column label="账号状态" prop="userStatusId" width="120">
        <template #default="scope">
          <el-switch
              v-model="scope.row.userStatusId"
              :active-value="0"
              :inactive-value="1"
              @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="等级" prop="level" width="60"/>
      <el-table-column label="个人简介" prop="briefly"/>
      <!--      <el-table-column fixed="right" label="操作" width="150">-->
      <!--        <template #default="scope">-->
      <!--          <el-button type="text" @click="handleEdit(scope.row)">更改</el-button>-->
      <!--          <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
    </el-table>

    <!-- 分页区域 -->
    <el-pagination
        :current-page="pagination.currentPage"
        :page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :pager-count="5"
        next-text="下一页"
        prev-text="上一页"
        style="margin-top: 20px; text-align: right"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />

    <!-- 封禁用户模态框 -->
    <el-dialog
        v-model="banDialog"
        :before-close="closeBanDialog"
        title="封禁用户"
        width="500px"
    >
      <el-form :model="banForm" label-width="100px" style="margin-top: 20px;">
        <el-form-item disabled label="用户ID">
          <div class="id-display-container">
            <el-tag
                v-for="id in banForm.userIds"
                :key="id"
                class="id-tag"
                type="default"
            >
              {{ id }}
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item label="封禁类型" required>
          <el-select
              v-model="banForm.userBanType"
              placeholder="请选择封禁类型"
              style="width: 100%"
          >
            <el-option label="临时封禁" value="temporary"/>
            <el-option label="永久封禁" value="permanent"/>
          </el-select>
        </el-form-item>
        <el-form-item label="封禁原因" required>
          <el-input
              v-model="banForm.userReason"
              placeholder="请输入封禁原因"
              rows="4"
              type="textarea"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeBanDialog">取消</el-button>
        <el-button type="primary" @click="confirmBan">确认封禁</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.user-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  min-height: calc(100vh - 150px);
}

.search-form {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 6px;
}

.operation-buttons {
  margin-bottom: 20px;
}

.operation-buttons .el-button {
  margin-right: 10px;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 6px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  font-weight: 600;
}

/* 用户ID标签样式（与文章ID标签保持一致） */
.id-display-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 6px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  min-height: 34px;
  align-items: center;
  width: 100%;
  box-sizing: border-box;
}

.id-tag {
  background-color: #f5f7fa;
  color: #4e5969;
  border: 1px solid #e5e6eb;
  border-radius: 4px;
  padding: 2px 10px;
  font-size: 14px;
  height: auto;
  line-height: 1.5;
}
</style>